var params = {
    target: "web",
    loop: false
}

var player = new QMplayer(params);

//秒转换分:秒
function duration(sec) {
    var time = sec;
    var hour_t = 0;
    var sec_t = 0;

    while (time >= 60) {
        time -= 60;
        hour_t++;
    }
    sec_t = Math.round(time);
    return (hour_t + ' : ' + (sec_t < 10 ? ('0' + sec_t) : sec_t));
}
//解析分享链接
var musicdata = '';
var audioObj = document.querySelector("audio");

function parsing(url) {
    //用于分享链接匹配的正则表达式
    var urlRegexp = /https:[\/]{2}c.y.qq.com\/base\/fcgi-bin\/u\?[\_]{2}=[A-Za-z0-9]+/;

    //用于截取分享链接的正则变道式
    var afterRegExp = /https:[\/]{2}c.y.qq.com\/base\/fcgi-bin\/u\?[\_]{2}=[A-Za-z0-9]+$/;
    var qmurl = $(url).val();

    if (urlRegexp.test(qmurl)) {

        qmurl = qmurl.substring(qmurl.indexOf('https'));
        while (!afterRegExp.test(qmurl)) {
            qmurl = qmurl.substring(0, qmurl.length - 1);
        }

        musicdata = '';
        $.ajax({
            sync: false,
            type: 'POST',
            dataType: 'json',
            url: '/parsing',
            data: {
                url: qmurl,
            },
            success: function (result) {
                if (result != '404') {

                    musicplay(result);

                    audioObj.addEventListener("play", getMusic, false);

                    $('audio')[0].addEventListener("durationchange", getMusic(result));
                }
                else {
                    prompt('分享的音乐不存在');
                    $(url).val('');
                }
            }
        })
    }
    else {
        prompt('不是正确的链接格式');
        $(url).val('');
    }
}




audioObj.addEventListener("durationchange", function () {
    console.log('已切歌')
}, false);

//获取解析信息
getMusic = function getMusic() {

    prompt('链接解析完成');
    musicdata = {
        songid: player.data.song.id,
        songname: player.data.song.name,
        duration: player.data.duration,
    }

    console.log(musicdata);

    audioObj.removeEventListener("play", getMusic, false);
}

//增加音乐
function musicadd() {
    if (musicdata != '') {
        $.ajax({
            sync: false,
            type: 'POST',
            dataType: 'json',
            url: '/musicadd',
            data: musicdata,
            success: function (result) {
                if (result == '200') {
                    prompt('音乐添加成功');
                    player.pause();
                    $('#musicUrl').val('');
                    musiclibrary();
                }
                else if (result == 'repeat') {
                    prompt('音乐库内有重复的音乐');
                    $('#musicUrl').val('');
                    player.pause();
                }
                else {
                    prompt('音乐添加失败');
                    player.pause();
                }

            }
        })
    }
    else {
        prompt('没有分享链接');
    }

}

//切换播放状态
function switchpause(obj, songid) {
    //当前未播放音乐
    if (player.state == 'ready') {
        musicplay(songid);
        $(obj).find('.fa-play').css('font-weight', '600');
        $(obj).parents('li').siblings().find('.fa-play').css('font-weight', '500');
    }
    //当前选择歌曲正在播放
    else if ($(obj).find('.fa-play').css('font-weight') == '600' && player.state == 'playing') {
        $(obj).find('.fa-play').css('font-weight', '500');
        player.pause();
    }
    //当前选择歌曲未播放
    else if ($(obj).find('.fa-play').css('font-weight') == '500' && player.state == 'playing') {
        $(obj).find('.fa-play').css('font-weight', '600');
        $(obj).parents('li').siblings().find('.fa-play').css('font-weight', '500');
        musicplay(songid);
    }
    //当前已暂停
    else if (player.state == 'pause' || player.state == 'error') {
        musicplay(songid);
        $(obj).find('.fa-play').css('font-weight', '600');
    }
    //音乐播放结束后随机切歌
    player.on("ended", function () {
        $(obj).find('.fa-play').css('font-weight', '500');
        $('#scrolllist').find('li').eq(Math.floor(Math.random() * (listlength - 1))).find('.songplay').trigger("click");
    })
    //播放错误
    player.on("error", function () {
        $(obj).find('.fa-play').css('font-weight', '500').parents('li').siblings().find('.fa-play').css('font-weight', '500');
    })
}


var listlength;
//获取音乐库
var songidlist = new Array;
function musiclibrary() {
    var musiclist = '';
    songidlist = new Array;

    $.ajax({
        type: 'POST',
        dataType: 'json',
        url: '/musiclist',
        success: function (result) {
            result.forEach(function (item) {
                songidlist.push(item);
                var error = 'fa-plus';
                if (item.state != 0)
                    error = 'fas fa-exclamation';
                else
                    error = 'fa fa-plus';

                musiclist += `
                    <li>
                        <div class="songmsg">
                            <p class="songname">${item.name}</p>
                            <p class="songduration">${duration(item.duration)}</p>
                        </div>
                        <div class="controls">
                            <button class="songplay" onclick="switchpause(this,'${item.songid}')">
                                <p class="fa fa-play"></p>
                            </button>
                            <button class="songdel" onclick="musicdel('${item.songid}')">
                                <p class="${error}"></p>
                            </button>
                        </div
                    </li>
                `
            });
            setTimeout(() => {
                listlength = $('#scrolllist').find('li').length;
            });
            document.getElementById('scrolllist').innerHTML = musiclist;
        }
    })
}


//播放音乐
function musicplay(songid) {
    player.off("play");
    player.off("pause");
    player.playReady();
    setTimeout(() => {
        player.play(songid);
    })
}
//报错状态标记
function state(state, songid) {
    $.ajax({
        type: 'POST',
        data: 'json',
        url: '/musicerror',
        data: {
            state: state,
            songid: songid,
        }
    });
}
//错误自动切歌/报错标记
// player.on("error", function () {
//     if (songid[playmid].songstate != '1') {
//         state('1', player.data.song.mid);
//     }
// })

//处理无法播放的音乐
player.on("error", function () {
    songidlist.forEach(function (item) {
        if (player.data.song.mid == item.songid) {
            if (confirm('“'+ item.name + '”无法播放，是否移除'))
                musicdel(item.songid);
            else
                if (item.songstate != '1') {
                    state('1', player.data.song.mid);
                }

        }

    })
    $('#musicUrl').val('');
})

//消除报错
player.on("playing",function(){
    if (item.songstate != '0') {
        state('0', player.data.song.mid);
    }
})

//删除音乐
function musicdel(songid) {
    if (confirm('删除操作无法逆转')) {
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: '/musicdel',
            data: {
                songid: songid
            },
            success: function (result) {
                if (result == '200') {
                    prompt('删除成功');
                    musiclibrary();
                }
                else {
                    prompt('删除失败');
                }
            }
        })
    }
}